package cn.congine.wizarpos.mall.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;

public class SessionFilter extends OncePerRequestFilter {

	private static Log log = LogFactory.getLog(SessionFilter.class);

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		// 包含以下任一字符串的uri无需过滤
		// 双斜线代表目录
		String[] unfilteredURIs = new String[] { "/login.html", "/user/login",
				"/styles/", "/js/", "/common/", "/merchant/", "/images/",
				"/merchant_images/", "/vip/", "/wechat/receive_notify",
				"/oauth/", "/news/", "/merchant_card/", "/comcashier/",
				"/bill/", "/electric/", "/ticket/", "/merchantAdminBind/",
				"/bankCardBind/bind", "/bankCardBind/getMyBankCard" };
		// 当前请求uri
		String uri = request.getRequestURI();

		// 判断当前uri是否需要过滤
		boolean doFilter = true;
		for (String unfilteredURI : unfilteredURIs) {
			// 如果uri中包含不过滤的字符串
			if (uri.indexOf(unfilteredURI) != -1) {
				doFilter = false;
				break;
			}
		}

		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);
		response.setHeader("Pragma", "no-cache");

		if (doFilter) {// 执行过滤 说明该请求URI需要用户先登录
			HttpSession session = request.getSession(false);
			if (session == null) {// 娶不到session 说明未登录
				log.warn("未登录或session失效:" + uri);
				// 如果是ajax请求响应头会有，x-requested-with
				if (request.getHeader("X-Requested-With") != null
						&& request.getHeader("X-Requested-With")
								.equalsIgnoreCase("XMLHttpRequest")) {
					// 在响应头设置session状态
					response.setHeader("sessionstatus", "timeout");
					response.getOutputStream().write("{}".getBytes());
				} else {
					response.sendRedirect(request.getContextPath()
							+ "/login.html");
				}

			} else {// 已登录 放行
				filterChain.doFilter(request, response);
			}
		} else {// 无须过滤 放行
			filterChain.doFilter(request, response);
		}
	}
}